//
//  Functions.swift
//  Space Experiment Module
//
//  Created by 曹亚索 on 2020/12/19.
//

import SpriteKit

//数据源

//上航道
let sideup = UIScreen.main.bounds.midY + 60
//下航道
let sidedown = UIScreen.main.bounds.midY - 60
//阶段加速
var speed1 : Bool = false
var speed2 : Bool = false
var speed3 : Bool = false
var speed4 : Bool = false
var speedArray : [Bool] = []

//生命值数组自动化生成
var healthArray : [SKSpriteNode] = []
let percentX = UIScreen.main.bounds.maxX / 40
var positionXArray : [CGFloat] = []
func setupHealthArray(num:Int){
    for i in 0...num-1{
        let health = SKSpriteNode()
        healthArray.append(health)
        let position = UIScreen.main.bounds.maxX - CGFloat(2 + i * 3) * percentX
        positionXArray.append(position)
    }
}

let percentY = UIScreen.main.bounds.maxY / 40
let positionY = UIScreen.main.bounds.maxY - 4 * percentY

//MARK:精灵初始化
func setupSprite(sourceName:String,width:CGFloat,height:CGFloat,positionX:CGFloat,positionY:CGFloat,sender:SKNode,UIntNum:UInt32)->SKSpriteNode{
    var sourceId = sourceName
    var characterWidth = width
    //角色宽度设定
    if sourceName == ""{
        sourceId = characterIdArray[currentCharacter]
        switch currentCharacter {
        case 0:
            characterWidth = 40 * 610/572
        case 1:
            characterWidth = 40 * 278/545
        case 2:
            characterWidth = 40 * 610/1093
        default:
            break
        }
    }
    let sprite = SKSpriteNode(texture: SKTexture(imageNamed: sourceId), size: CGSize(width: characterWidth, height: height))
    sprite.position = CGPoint(x: positionX, y: positionY)
    sprite.physicsBody = SKPhysicsBody(circleOfRadius: width / 2)
    let categoryBitMask : UInt32 = UIntNum
    sprite.physicsBody?.categoryBitMask = categoryBitMask
    sprite.physicsBody?.contactTestBitMask = 2
    sender.addChild(sprite)
    return sprite
}

//MARK:精灵移动脚本
func spriteMove(sprite:SKSpriteNode,speed:CGFloat,deltaTime:TimeInterval){
    var pointX = sprite.position.x
    var pointY = sprite.position.y
    pointX -= speed * CGFloat(deltaTime)
    //出屏幕时
    if pointX <= -sprite.size.width / 2{
        let a = Int.random(in: 1...2)
        pointX = UIScreen.main.bounds.width + sprite.size.width + CGFloat(Int.random(in: 0...1000))
        if a == 1{
            pointY = sideup
        }else{
            pointY = sidedown
        }
    }
        sprite.position = CGPoint(x: pointX, y: pointY)
}

//MARK:游戏血条初始化
func setupHealth(sender:SKNode,health:Int){
    for i in 0...health-1{
        let sprite = SKSpriteNode(texture: SKTexture(image: heart1), size: CGSize(width: 40, height: 40))
        sprite.position = CGPoint(x: positionXArray[i], y: positionY)
        healthArray[i] = sprite
        sender.addChild(healthArray[i])
    }
}


